package util

import (
	"encoding/json"
	"fmt"
	"log"
	"net/http"
	"strconv"
	"strings"
	"time"

	"mumu_stock_trad/model"

	_ "github.com/go-sql-driver/mysql" // MySQL driver
)

// Parse JSON response
var response struct {
	Showapi_res_error string `json:"showapi_res_error"`
	Showapi_res_code  int    `json:"showapi_res_code"`
	Showapi_res_body  struct {
		Pagebean struct {
			AllPages    int    `json:"allPages"`
			Name        string `json:"name"`
			CurrentPage int    `json:"currentPage"`
			AllNum      int    `json:"allNum"`
			TypeId      string `json:"typeId"`
			MaxResult   int    `json:"maxResult"`
			Contentlist []struct {
				Totalcapital_val string `json:"totalcapital_val"`
				Market           string `json:"market"`
				Currcapital_val  string `json:"currcapital_val"`
				Name             string `json:"name"`
				Code             string `json:"code"`
			} `json:"contentlist"`
		} `json:"pagebean"`
	} `json:"showapi_res_body"`
}

func FetchStockList(page int, typeId string) ([]model.StockList, interface{}, int, error) {
	// ShowAPI endpoint and key
	url := "https://route.showapi.com/131-59"
	appKey := "c9A84EFCb2C34EEdaAACa3Dd3C1D7728"

	fmt.Println(fmt.Sprintf("page=%d&typeId=%s", page, typeId))
	// Prepare POST data
	data := strings.NewReader(fmt.Sprintf("page=%d&typeId=%s", page, typeId))

	// Create a new HTTP POST request
	req, err := http.NewRequest("POST", url, data)
	if err != nil {
		log.Fatalf("Failed to create HTTP request: %v", err)
	}

	// Set headers
	req.Header.Set("appKey", appKey)
	req.Header.Set("Content-Type", "application/x-www-form-urlencoded")

	// Send HTTP request
	client := &http.Client{}
	resp, err := client.Do(req)
	if err != nil {
		log.Fatalf("HTTP POST request failed: %v", err)
	}
	defer resp.Body.Close()

	// Check HTTP status
	if resp.StatusCode != http.StatusOK {
		log.Fatalf("HTTP request failed with status code: %d", resp.StatusCode)
	}

	err = json.NewDecoder(resp.Body).Decode(&response)
	if err != nil {
		log.Fatalf("Failed to decode JSON response: %v", err)
	}

	// Check ShowAPI response code
	if response.Showapi_res_code != 0 {
		log.Fatalf("ShowAPI request failed: %s", response.Showapi_res_error)
	}

	list := []model.StockList{}

	// Process and save stocks to the database
	for _, item := range response.Showapi_res_body.Pagebean.Contentlist {
		// Convert totalcapital_val and currcapital_val to float64
		totalCapital, err := strconv.ParseFloat(item.Totalcapital_val, 64)
		if err != nil {
			log.Printf("Failed to parse totalcapital_val: %v", err)
			continue
		}
		currentCapital, err := strconv.ParseFloat(item.Currcapital_val, 64)
		if err != nil {
			log.Printf("Failed to parse currcapital_val: %v", err)
			continue
		}

		// Create a Stock object
		stock := model.StockList{
			Code:           item.Code,
			Name:           item.Name,
			Market:         item.Market,
			TotalCapital:   totalCapital,
			CurrentCapital: currentCapital,
			CreatedAt:      time.Now(), // Assuming this represents the insertion time
			AllNum:         response.Showapi_res_body.Pagebean.AllNum,
			CategoryName:   response.Showapi_res_body.Pagebean.Name,
			TypeID:         response.Showapi_res_body.Pagebean.TypeId,
		}

		list = append(list, stock)
	}

	fmt.Println("Stocks data saved successfully!")

	return list, response, response.Showapi_res_body.Pagebean.AllPages, nil
}
